package com.weike.yuanding.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weike.yuanding.core.domain.R;
import com.weike.yuanding.entity.SessionEntity;
import com.weike.yuanding.entity.SessionMessageEntity;
import com.weike.yuanding.entity.SessionUserEntity;
import com.weike.yuanding.entity.UserEntity;
import com.weike.yuanding.mapper.*;
import com.weike.yuanding.utils.BaseContext;
import com.weike.yuanding.vo.UserMessageResVo;
import com.weike.yuanding.vo.UserSessionResVo;
import com.weike.yuanding.ws.WebsocketController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: MessageController
 * @Author: YuanDing
 * @Date: 2025/4/12 14:40
 * @Description:
 */

@RestController
@RequestMapping("user/message")
public class MessageController {

    @Autowired
    private UserFriendMapper userFriendMapper;

    @Autowired
    private SessionMapper sessionMapper;

    @Autowired
    private SessionUserMapper sessionUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SessionMessageMapper sessionMessageMapper;

    @Autowired
    private WebsocketController websocketController;

    @Autowired
    private RedisTemplate<String , String> redisTemplate;


    private static String USER_OLINE_KEY = "user:online:";

    @GetMapping("userList")
    public R getUserMessageList() {
        String userId = BaseContext.userId.get();

        List<UserSessionResVo> list = sessionMapper.selectListByUserId(userId);
        list.forEach(item -> {
            if (!StrUtil.isBlankIfStr(item.getUserId())) {
                String result = redisTemplate.opsForValue().get(USER_OLINE_KEY + item.getUserId());
                if (!StrUtil.isBlankIfStr(result)) {
                    item.setOnline(true);
                }
            }
        });
        return R.ok(list);
    }

    /**
     * 创建会话
     * @return
     */
    @PostMapping("create/{userId}")
    @Transactional
    public R createSession(@PathVariable("userId") String userId) {
        String myUserId = BaseContext.userId.get();
        UserEntity my = userMapper.selectById(myUserId);
        UserEntity user = userMapper.selectById(userId);


        HashMap<String, Object> searchMap = new HashMap<>();
        searchMap.put("userId" , userId);
        searchMap.put("myId" , myUserId);
        //　判断下有没有会话记录
        String sessionId1 = sessionUserMapper.selectSession(searchMap);

        if (StrUtil.isNotBlank(sessionId1)) {
            return R.ok(sessionId1);
        }

        SessionEntity sessionEntity = new SessionEntity();
        sessionEntity.setCreateUser(myUserId);
        sessionEntity.setType("0");
//        sessionUserEntity.set
        sessionMapper.insert(sessionEntity);
        String sessionId = sessionEntity.getId();

        SessionUserEntity sessionUserEntity = new SessionUserEntity();
        sessionUserEntity.setSessionId(sessionId);
        sessionUserEntity.setNickName(my.getName());
        sessionUserEntity.setUserId(myUserId);

        SessionUserEntity sessionUserEntity2 = new SessionUserEntity();
        sessionUserEntity2.setSessionId(sessionId);
        sessionUserEntity2.setNickName(user.getName());
        sessionUserEntity2.setUserId(userId);

        sessionUserMapper.insert(sessionUserEntity);
        sessionUserMapper.insert(sessionUserEntity2);

        return R.ok(sessionId);
    }


    /**
     * 获取会话信息列表
     * @return
     */
    @GetMapping("list/{sessionId}")
    public R list(@PathVariable("sessionId") String sessionId) {
        String myUserId = BaseContext.userId.get();
        if (StrUtil.isBlankIfStr(myUserId)) {
            return R.fail("请先登录！");
        }

        HashMap<String, Object> searchMap = new HashMap<>();
        searchMap.put("sessionId" , sessionId);
        List<SessionMessageEntity> sessionMessageEntities = sessionMessageMapper.list(searchMap);

        List<UserMessageResVo> resVoList = sessionMessageEntities.stream().map(item -> {
            UserMessageResVo userMessageResVo = new UserMessageResVo();
            userMessageResVo.setContent(item.getMessage());
            userMessageResVo.setSessionId(item.getSessionId());
            userMessageResVo.setDatetime(item.getCreateTime());
            userMessageResVo.setUrl(item.getImgUrl());
            userMessageResVo.setAvatar(item.getAvatar());
            userMessageResVo.setName(item.getName());
            userMessageResVo.setUserId(item.getUserId());
            userMessageResVo.setType(item.getType());
            return userMessageResVo;
        }).collect(Collectors.toList());

        return R.ok(resVoList);
    }


    /**
     * 获取会话信息列表
     * @return
     */
    @PostMapping("add")
    public R list(@RequestBody UserMessageResVo userMessageResVo) {
        String myUserId = BaseContext.userId.get();
        userMessageResVo.setUserId(myUserId);
        userMessageResVo.setDatetime(new Date());
        UserEntity user = userMapper.selectById(myUserId);
        userMessageResVo.setName(user.getName());
        userMessageResVo.setAvatar(user.getAvatar());

        // 以下这段开启新线程保存
        asyncSaveMessage(userMessageResVo, myUserId);


        websocketController.sendMessage(userMessageResVo);
        return R.ok();
    }
    // 使用@Async实现异步保存
    @Async("taskExecutor")
    public void asyncSaveMessage(UserMessageResVo userMessageResVo, String userId) {
        try {
            SessionMessageEntity sessionMessageEntity = new SessionMessageEntity();
            sessionMessageEntity.setUserId(userId);
            sessionMessageEntity.setImgUrl(userMessageResVo.getUrl());
            sessionMessageEntity.setSessionId(userMessageResVo.getSessionId());
            sessionMessageEntity.setMessage(userMessageResVo.getContent());
            sessionMessageEntity.setType(userMessageResVo.getType());
            sessionMessageMapper.insert(sessionMessageEntity);
        } catch (Exception e) {
            System.err.println("异步保存消息记录失败");
        }
    }
}
